import { app, BrowserWindow } from "electron";
import { fileURLToPath } from "node:url";
import path from "node:path";
import windowStateKeeper from "electron-window-state";
import "./main/ipc";
import "./main/spider";
import { registerWindowIpcInvoker } from "@elec/main/ipc/window.ts";
import { registerDialogInvoker } from "@elec/main/ipc/dialog.ts";
import { registerWindowHolder } from "@elec/main/util/window-holder";
import "./main/modules";

const __dirname = path.dirname(fileURLToPath(import.meta.url));

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.mjs
// │
process.env.APP_ROOT = path.join(__dirname, "..");
// 禁用安全警告
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = "true";

// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
export const VITE_DEV_SERVER_URL = process.env["VITE_DEV_SERVER_URL"];
export const MAIN_DIST = path.join(process.env.APP_ROOT, "dist-electron");
export const RENDERER_DIST = path.join(process.env.APP_ROOT, "dist");
const IS_DEV = process.env.NODE_ENV === "development";

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, "public") : RENDERER_DIST;

let mainWindow: BrowserWindow | null;

function stateKeeper() {
  return windowStateKeeper({
    defaultWidth: 1600,
    defaultHeight: 900,
    maximize: true,
  });
}

async function createMainWindow(state: windowStateKeeper.State) {
  mainWindow = new BrowserWindow({
    icon: path.join(process.env.VITE_PUBLIC, "devil.png"),
    center: true,
    width: state.width,
    height: state.height,
    x: state.x,
    y: state.y,
    minWidth: 1600,
    minHeight: 900,
    // frame: false,
    title: "DevilBox",
    // useContentSize: true,
    titleBarStyle: "hidden",
    // titleBarOverlay: false,
    webPreferences: {
      preload: path.join(__dirname, "preload.mjs"),
      nodeIntegration: false,
      nodeIntegrationInWorker: false,
      contextIsolation: true,
      webSecurity: false, // 这个设为false，否则无法加载本地图片等资源
      enableWebSQL: false,
      spellcheck: false,
    },
    show: false,
  });
  registerWindowHolder(mainWindow);
  registerWindowIpcInvoker(mainWindow);
  registerDialogInvoker(mainWindow);

  // 删除默认菜单
  mainWindow.removeMenu();
  // 管理窗口状态
  state.manage(mainWindow);

  mainWindow.webContents.on("did-finish-load", () => {
    // 前端加载完成
    if (IS_DEV) {
      mainWindow!.webContents.openDevTools({ mode: "detach" });
    }
  });

  if (VITE_DEV_SERVER_URL) {
    await mainWindow.loadURL(VITE_DEV_SERVER_URL);
    // mainWindow.loadURL("https://www.antdv.com/components/date-picker-cn").catch(() => void 0);
  } else {
    // win.loadFile('dist/index.html')
    await mainWindow.loadFile(path.join(RENDERER_DIST, "index.html"));
  }

  mainWindow.show();
}

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
    mainWindow = null;
  }
});

app.on("activate", () => {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createMainWindow(stateKeeper()).catch(() => void 0);
  }
});

app.on("quit", () => {});

app.whenReady().then(() => {
  createMainWindow(stateKeeper()).catch(() => void 0);
});
